package com.aydx.minirpc.core.spring;

import com.aydx.minirpc.core.MiniRpcException;
import com.aydx.minirpc.core.common.ClassUtils;
import com.aydx.minirpc.core.common.StringTools;
import com.aydx.minirpc.core.RemoteCallPackage;
import com.aydx.minirpc.core.server.AnswerRemoteCall;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;

/**
 * 适用于spring的响应器
 */
public class SpringAnswerRemoteCall extends AnswerRemoteCall {
    private Logger logger = LoggerFactory.getLogger(SpringAnswerRemoteCall.class);
    private ApplicationContext context;

    public SpringAnswerRemoteCall(ApplicationContext context){
        this.context=context;
    }


    @Override
    public byte[] execute(RemoteCallPackage callPackage) {
        try{
            if(StringTools.isEmpty(callPackage.getInterfaceName())){
                throw new NullPointerException("interfaceName不能为空");
            }
            Class clazz=Class.forName(callPackage.getInterfaceName());
            Method method = clazz.getMethod(callPackage.getMethod().getMethod(), ClassUtils.forNames(callPackage.getMethod().getArgsClassName()));//得到方法对象
            Object result = method.invoke(this.context.getBean("provider_"+callPackage.getInterfaceName()),callPackage.getArgs());//调用借钱方法，得到返回值
            return getRpcContext().getSerializableFactory().serialize(result);
        }catch (Exception e){
            logger.error("调用时发生异常",e);
            throw new MiniRpcException("调用时发生异常",e);
        }
    }

    public ApplicationContext getContext() {
        return context;
    }

    public void setContext(ApplicationContext context) {
        this.context = context;
    }
}
